接下來幾天,我們要一起完成一個小專案。這個專案會包含 四個簡單的 Sub Agent 和一個 Master Agent(Root Agent)。
為了讓大家更容易理解流程,我會先用 FastAPI 來模擬每個 Agent 的輸入與輸出,確認邏輯能不能順利跑通,再逐步轉換成符合 Google ADK Agent 的形式。
特別提醒:
不會串接真實 API,所有資料都會用「模擬」的方式來呈現。
這篇要完成的第一支 Agent,就是 飯店搜尋 Agent。
我們這次會先用 FastAPI 做基本實作,下一篇再帶大家把它轉成正式的 Agent。
from fastapi import FastAPI, HTTPException
app = FastAPI(
title="飯店搜尋 Agent API",
description="一個簡單的 AI Agent,用於搜尋飯店資訊。",
version="1.0.0",
)
# 模擬飯店資料庫
HOTEL_DATABASE = {
"Taipei": [
{"name": "Taipei Grand Hotel", "stars": 5, "price": 4000},
{"name": "Hotel Proverbs Taipei", "stars": 4, "price": 3000},
{"name": "Cosmos Hotel Taipei", "stars": 3, "price": 2000},
{"name": "Caesar Park Hotel", "stars": 4, "price": 3500},
],
"Tokyo": [
{"name": "Park Hyatt Tokyo", "stars": 5, "price": 50000},
{"name": "Shinjuku Granbell Hotel", "stars": 4, "price": 20000},
{"name": "Hotel Sunroute Plaza", "stars": 3, "price": 15000},
],
"New York": [
{"name": "The Plaza", "stars": 5, "price": 700},
{"name": "Pod 51 Hotel", "stars": 3, "price": 200},
{"name": "Arlo SoHo", "stars": 4, "price": 350},
],
}
@app.post("/search_hotels")
def search_hotels(city: str):
"""
呼叫飯店搜尋 Agent,根據城市名稱回傳最多 3 家飯店資料。
"""
try:
city = city.strip()
if not city:
raise ValueError("City name is required.")
hotels = HOTEL_DATABASE.get(city, [])
result = hotels[:3]
if not result:
return {"status": "error", "message": f"No hotels found for city '{city}'."}
return {"status": "success", "city": city, "hotels": result}
except Exception as e:
raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
app = FastAPI(...)
:建立 FastAPI 應用,設定 API 文件標題與描述(Swagger UI)。HOTEL_DATABASE
:模擬資料庫(實務上會連接真實 DB 或外部 API)。@app.post("/search_hotels")
:定義一個 POST 路由。city = city.strip()
:處理輸入字串,去掉多餘空白。hotels = HOTEL_DATABASE.get(city, [])
:從模擬資料庫抓出飯店清單。result = hotels[:3]
:只回傳最多三筆結果。HTTPException
:用來回傳 500 錯誤訊息。啟動方式:
uvicorn HotelSearchAgent:app --host 0.0.0.0 --port 5678 --reload
Taipei
Tokyo
New York